import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    Image,
    TouchableOpacity,
    InteractionManager,
    ScrollView
} from 'react-native';
import FastImage from 'react-native-fast-image'
import {UltimateListView} from "react-native-ultimate-listview";
import {LoaderScreen, View} from 'react-native-ui-lib'
import {Toast} from 'teaset'

//自定义文件
import Global from '../common/global'
import colors from '../common/colors'
import Api from "../common/api";
import Util from "../common/util";

export default class IndexPage extends Component {
    static navigationOptions = ({navigation, screenProps}) => ({
        title: '首页',
        color: colors.primaryColor,
        tabBarIcon: ({focused, tintColor}) => {
            if (focused) {
                return (
                    <Image source={require('../images/tabbar_icon_homed.png')}
                           style={{width: 25, height: 25}}
                    />
                )

            } else {
                return <Image source={require('../images/tabbar_icon_home.png')}
                              style={{width: 25, height: 25}}
                />
            }
        },
        headerBackTitle: null
    })


    constructor(props) {
        super(props);
        this.state = {
            loadError: false,
            weather: {}
        };
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            Util.fetchPost(Api.api, {})
                .then(({code, msg, data}) => {
                    if (code == '0') {
                        this.setState({
                            weather: data.weather
                        })
                    }
                }).catch(error => {
                console.log(error)
            });
        })
    }

    renderHeader = () => {
        return (
            <View style={{
                height: Global.headerHeight,
                width: Global.width,
                paddingTop: Global.paddingTop,
                alignItems: 'center',
                justifyContent: 'space-between',
                backgroundColor: '#176DD7',
                flexDirection: 'row',
                paddingHorizontal: 16
            }}>
                <Text style={{
                    fontSize: 13,
                    color: '#fff',
                    fontWeight: 'bold',
                }}>首页</Text>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    {
                        this.state.weather.icon ? (
                            <FastImage style={{width: 23, height: 23, marginRight: 5}}
                                       source={{uri: this.state.weather.icon}}
                            />
                        ) : null
                    }
                    <Text style={{
                        fontSize: 12,
                        color: '#fff',
                    }}>
                        {this.state.weather.desc} {this.state.weather.scope}
                    </Text>
                </View>
            </View>
        )
    }

    pressMenu = (page, params = {}) => {
        this.props.navigation.navigate(page, params)
    }

    renderMenu = () => {
        return (
            <View style={{
                width: Global.width,
                backgroundColor: '#fff',
                padding: 15,
                flexDirection: 'row',
                flexWrap: 'wrap',
            }}>
                <TouchableOpacity style={{marginRight: 5}} activeOpacity={0.8}
                                  onPress={() => this.pressMenu('WeatherList')}>
                    <View style={[styles.menuContainer, {backgroundColor: '#5683E8'}]}>
                        <Image style={{width: 52, height: 55, marginBottom: 20}}
                               source={require('../images/home_ico_01.png')}/>
                        <Text style={styles.menuText}>渤海中尺度气象数据</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity activeOpacity={0.8} onPress={() => this.pressMenu('GlobalMap')}>
                    <View style={[styles.menuContainer, {backgroundColor: '#6CCF55'}]}>
                        <Image style={{width: 99, height: 49, marginBottom: 11}}
                               source={require('../images/home_ico_02.png')}/>
                        <Text style={styles.menuText}>风、气象、海洋</Text>
                        <Text style={[styles.menuText, {marginTop: 5}]}>状况全球地图</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity style={{marginRight: 5, marginTop: 5}} activeOpacity={0.8}
                                  onPress={() => this.pressMenu('ShuZhiYuBao')}>
                    <View style={[styles.menuContainer, {backgroundColor: '#3F9FEE'}]}>
                        <Image style={{width: 55, height: 55, marginBottom: 21}}
                               source={require('../images/home_ico_03.png')}/>
                        <Text style={styles.menuText}>数值预报</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity style={{marginTop: 5}} activeOpacity={0.8}
                                  onPress={() => this.pressMenu('HuanJingJianCe')}>
                    <View style={[styles.menuContainer, {backgroundColor: '#13BDA2'}]}>
                        <Image style={{width: 96, height: 46, marginBottom: 26}}
                               source={require('../images/home_ico_04.png')}/>
                        <Text style={styles.menuText}>海洋环境监测</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity style={{marginRight: 5, marginTop: 5}} activeOpacity={0.8}
                                  onPress={() => this.pressMenu('ZaiHaiList')}>
                    <View style={[styles.menuContainer, {backgroundColor: '#FBC223'}]}>
                        <Image style={{width: 40, height: 49, marginBottom: 15}}
                               source={require('../images/home_ico_05.png')}/>
                        <Text style={styles.menuText}>突发灾害预警</Text>
                        <Text style={[styles.menuText, {marginTop: 5}]}>查询和处理结果</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity style={{marginTop: 5}} activeOpacity={0.8}
                                  onPress={() => this.pressMenu('ZaiHaiLuRu')}>
                    <View style={[styles.menuContainer, {backgroundColor: '#FF5E53'}]}>
                        <Image style={{width: 44, height: 50, marginBottom: 25}}
                               source={require('../images/home_ico_06.png')}/>
                        <Text style={styles.menuText}>突发灾害录入</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity style={{marginRight: 5, marginTop: 5}} activeOpacity={0.8}
                                  onPress={() => this.pressMenu('TaskList', {from: 'receive', title: '收到的指派'})}>
                    <View style={[styles.menuContainer, {backgroundColor: '#FF3F6D'}]}>
                        <Image style={{width: 40, height: 49, marginBottom: 15}}
                               source={require('../images/home_ico_07.png')}/>
                        <Text style={styles.menuText}>任务指派</Text>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity style={{marginTop: 5}} activeOpacity={0.8} onPress={() => this.pressMenu('Notice')}>
                    <View style={[styles.menuContainer, {backgroundColor: '#8E3BD4'}]}>
                        <Image style={{width: 50, height: 50, marginBottom: 25}} resizeMode={"contain"}
                               source={require('../images/home_ico_08.png')}/>
                        <Text style={styles.menuText}>公告信息</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    renderTitle = () => {
        return (
            <View style={{paddingTop: 15, backgroundColor: '#fff', paddingLeft: 15, paddingBottom: 5}}>
                <Text style={{
                    fontSize: 20,
                    color: '#333333',
                }}>
                    任务指派
                </Text>
            </View>
        )
    }


    renderItem = (item) => {
        return (
            <TouchableOpacity activeOpacity={0.8} onPress={() => this.pressItem(item)}>
                <View padding-15 bg-white style={{justifyContent: 'space-between'}}>
                    <View row centerV width={Global.width - 30} style={{justifyContent: 'space-between'}}>
                        <Text text80 style={{color: '#333333'}}>
                            {item.name}
                        </Text>
                        <Text text100 style={{color: '#AEAEAE'}}>
                            {item.ctime}
                        </Text>
                    </View>
                    <View row centerV marginT-10 width={Global.width - 30} style={{justifyContent: 'space-between'}}>
                        <Text text80 style={{color: '#333333', flex: 1}}>
                            {/*{item.wd}°N,{item.jd}°E*/}
                        </Text>
                        <Text text95 style={{color: '#176DD7'}}>
                            查看详情
                        </Text>
                        <Image style={{width: 17, height: 17}} source={require('../images/ico_go.png')}/>
                    </View>

                </View>
            </TouchableOpacity>
        )
    }

    pressItem = (item) => {
        this.props.navigation.navigate('TaskDetail', {
            task: item,
            callback: () => {
                this.refs._listview.refresh()
            },
            from: 'receive'
        })
    }

    onFetch = (page = 1, startFetch, abortFetch) => {
        Util.fetchPost(Api.task, {uid: Global.uid, page, limit: Global.pageSize})
            .then(({code, msg, data}) => {
                if (code == 0) {
                    startFetch(data.list, Global.pageSize);
                } else {
                    abortFetch()
                }
            }).catch(error => {
            abortFetch(); //manually stop the refresh or pagination if it encounters network error
            console.log(error);
            Toast.fail('网络开小差了，请稍候再试');
        });
    };

    renderSeparator = () => {
        return (
            <View style={{height: 5, backgroundColor: colors.bgColor}}/>
        )
    }

    renderEmptyView = () => {
        return (
            <View style={{height: 100, backgroundColor: 'white', justifyContent: 'center', alignItems: 'center'}}>
                <Text style={{fontSize: 16, color: '#ccc'}}>暂未收到任务指派</Text>
            </View>
        )
    }

    renderPaginationFetchingView = () => {
        return (
            <View style={{height: 100, alignItems: 'center', justifyContent: 'center'}}>
                <LoaderScreen
                    color={colors.primaryColor}
                    message="加载中..."
                    overlay
                />
            </View>
        )
    }

    renderList = () => {
        return (
            <UltimateListView
                ref="_listview"
                onFetch={this.onFetch}
                keyExtractor={(item, index) => ("item" + index)}  //this is required when you are using FlatList
                refreshableMode={"basic"}//basic or advanced
                item={this.renderItem}  //this takes three params (item, index, separator)
                numColumns={1} //to use grid layout, simply set gridColumn > 1
                paginationFetchingView={this.renderPaginationFetchingView}
                waitingSpinnerText={"加载中..."}
                emptyView={this.renderEmptyView}
                separator={this.renderSeparator}
                allLoadedText={""}
            />
        )
    }

    render() {
        return (
            <View style={styles.container}>
                {this.renderHeader()}
                <ScrollView style={{flex: 1}}>
                    {this.renderMenu()}
                    {/*{this.renderTitle()}*/}
                    {/*{this.renderList()}*/}
                </ScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: colors.bgColor
    },
    menuContainer: {
        width: (Global.width - 35) / 2,
        height: (Global.width - 35) * 7 / 17,
        alignItems: 'center',
        justifyContent: 'center'
    },
    menuText: {
        fontSize: 13,
        color: '#fff',
    }
});
